<template>
  <van-nav-bar
    :title="OPERTYPE == 'RESEND' ? t('home.打单签出') : t('home.打印')"
    left-arrow
    @click-left="onClickLeft"
  />
  <div class="p-2 mx-auto">
    <!-- <van-radio-group v-model="checked">
      <div class="flex justify-around h-10 mb-2">
        <van-radio name="1" >
          <template #icon="props">
            <span
              class="p-5"
              :class="
                props.checked
                  ? 'bg-green-500  text-white '
                  : 'text-gray-400 round bg-white text-black  '
              "
              >{{ t("printPage.换运单号") }}</span
            >
          </template>
        </van-radio>
        <van-radio name="2">
          <template #icon="props">
            <span
              class="p-5"
              :class="
                props.checked
                  ? 'bg-green-500 round text-white  '
                  : 'text-gray-400 round bg-white text-black  '
              "
              >{{ t("printPage.换重发单号") }}</span
            >
          </template>
        </van-radio>
        <van-radio name="3">
          <template #icon="props">
            <span
              class="p-5"
              :class="
                props.checked
                  ? 'bg-green-500 round text-white '
                  : 'text-gray-400 round bg-white text-black   '
              "
              >{{ t("printPage.打印条码") }}</span
            >
          </template>
        </van-radio>
      </div>
    </van-radio-group> -->

    <van-radio-group v-model="checked">
      <van-cell-group class="flex111">
        <van-cell :title="t('printPage.换运单号')" clickable @click="checked = '1'">
          <template #right-icon>
            <van-radio name="1" />
          </template>
        </van-cell>
        <van-cell :title="t('printPage.换重发单号')" clickable @click="checked = '2'">
          <template #right-icon>
            <van-radio name="2" />
          </template>
        </van-cell>
        <van-cell :title="t('printPage.打印条码')" clickable @click="checked = '3'">
          <template #right-icon>
            <van-radio name="3" />
          </template>
        </van-cell>
      </van-cell-group>
    </van-radio-group>

    <!-- 条码 -->
    <van-field
      id="scan_order"
      v-model="scan"
      :placeholder="t('printPage.请扫描条码')"
      @keydown.enter="handleScan"
    />
    <Tip :state="tipState" />
    <Tip :state="tipState2" />
    <Tip
      :state="tipStateFlag"
      :style="tipState4.info || tipState3.info ? '' : 'display:none'"
    />
    <Tip :state="tipState3" />
    <Tip :state="tipState4" />
  </div>
</template>

<script setup lang="ts">
// import { localStorage } from "@/utils/local-storage";
import { postRequest, postRequestParams } from "@/api";
// import { STORAGE_PRINTER_KEY } from "@/stores/mutation-type";
import router from "@/router";
import { DEPOT_CODE } from "@/utils/constant";
import { printUrl } from "@/utils/print";
import { showConfirmDialog } from "vant";
// import {
//   STORAGE_PRINTER_KEY,
// } from "@/stores/mutation-type";
// import { AppToast } from "@/utils/appToast";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

//Info
const tipState = reactive({
  color: "white",
  background: "white",
  info: "",
  infoClass: "",
});
//Scan
const tipState2 = reactive({
  color: "black",
  background: "white",
  info: "",
  infoClass: "",
  fontSize: "1.2rem",
});
const tipStateFlag = reactive({
  color: "black",
  background: "white",
  info: "⬇",
  infoClass: "",
  fontSize: "1.2rem",
});
// After number
const tipState3 = reactive({
  color: "black",
  background: "white",
  info: "",
  infoClass: "",
  fontSize: "1rem",
});
// After number Link
const tipState4 = reactive({
  color: "black",
  background: "white",
  info: "",
  infoClass: "",
  textAligin: "left",
  fontSize: "1rem",
});
const checked = ref("1");
const scan = ref("");
const OPERTYPE = ref("");
const onClickLeft = () => history.back();
const init = async () => {
  function getPathParamsByName(name) {
    const w = location.hash.indexOf('?');
    const query = location.hash.substring(w + 1);

    const vars = query.split('&');
    for (let i = 0; i < vars.length; i++) {
      const pair = vars[i].split('=');
      if (pair[0] == name) {
        return pair[1];
      }
    }
    return '';
  }
  // 获取路径参数
  OPERTYPE.value = getPathParamsByName("operType");
  // console.error(OPERTYPE.value)
  if (OPERTYPE.value == "RESEND") {
    checked.value = "2";
  }
};
init();

onMounted(() => {
  // scan_order  聚焦
  const scan_order = document.getElementById("scan_order");
  scan_order.focus();
});

const handleScan = () => {
  tipState.info = "";
  tipState2.info = "";
  tipState3.info = "";
  tipState4.info = "";

  if (scan.value == "" || scan.value == null) {
    tipState.info = t("printPage.请扫描条码");
    tipState.background = "red";
    return;
  }
  if (checked.value == "1") { //无头件打印
    // postRequest("/ReturnOrderService/claim/query", {
    //   depot: DEPOT_CODE,
    //   packageNumber: scan.value,
    //   offset: 0,
    //   limit: 1000,
    //   returnClaimed: false,
    //   waitForPrint: false,
    // }).then((res) => {
    //   if (res.status === 200) {
    //     if (res.data.length > 0 && res.data[0].advancedProviderNumber !=undefined) {
    //       handlePrint("https://center.j-net.cn/wlms/goods/print/sku?type=PDF_4x3&num=&remark=&codes="+res.data[0].advancedProviderNumber);
    //     } else {
    //       tipState2.info = scan.value + " " + t("printPage.未找到面单数据");
    //       tipState4.info = "";

    //       tipState.info = t("printPage.打印失败");
    //       tipState.background = "red";
    //       scan.value = "";
    //       return;
    //     }
    //   } else {
    //     tipState2.info = scan.value + " " + t("printPage.未找到面单数据");
    //     tipState4.info = "";

    //     tipState.info = t("printPage.打印失败");
    //     tipState.background = "red";
    //     scan.value = "";
    //     return;
    //   }
    // });

    postRequest("/ReturnOrderService/claim/printWaybillNumber?packageNumber="+scan.value, {
      depot: DEPOT_CODE,
      packageNumber: scan.value,
      offset: 0,
      limit: 1000,
      returnClaimed: false,
      waitForPrint: false,
    }).then((res) => {
      if (res.status === 200) {

        // if (res.data.length > 0 && res.data[0].advancedProviderNumber !=undefined) {
          // handlePrint("https://center.j-net.cn/wlms/goods/print/sku?type=PDF_4x3&num=&remark=&codes="+res.data[0].advancedProviderNumber);
          if (res.data.length > 0 ) {
            handlePrint(res.data)
        } else {
          tipState2.info = scan.value + " " + t("printPage.未找到面单数据");
          tipState4.info = "";

          tipState.info = t("printPage.打印失败");
          tipState.background = "red";
          scan.value = "";
          return;
        }
      } else {
        tipState2.info = scan.value + " " + t("printPage.未找到面单数据");
        tipState4.info = "";

        tipState.info = t("printPage.打印失败");
        tipState.background = "red";
        scan.value = "";
        return;
      }
    });

  }
  if (checked.value == "2") {
    postRequestParams("/ReturnOrderService/tms/return/retry/label", {
      packageNumber: scan.value,
    }).then((res) => {
      if (res.status == 200) {
        if (!res.data) {
          tipState2.info = scan.value + " " + t("printPage.未找到面单数据");
          tipState4.info = "";

          tipState.info = t("printPage.打印失败"); //+' '+res.message=='undefined'?'':res.message;
          tipState.background = "red";
          scan.value = "";
          return;
        } else {
          //发送data 给打印机
          console.log("发送data 给打印机");
          handlePrint(res.data);
          return;
        }
      } else {
        tipState2.info = scan.value + " " + res.message;
        tipState4.info = "";

        tipState.info = t("printPage.打印失败");
        tipState.background = "red";
        scan.value = "";
        return;
      }
    });
  }
  if (checked.value == "3") {
    if (scan.value.length < 5) {
      tipState2.info = scan.value + " " + t("printPage.请打印5位以上的条码");
      tipState4.info = "";

      tipState.info = t("printPage.打印失败");
      tipState.background = "red";
      scan.value = "";
      return;
    }
    handlePrint(
      "https://center.j-net.cn/wlms/goods/print/sku?type=PDF_4x3&num=&remark=&codes=" +
        scan.value
    );
  }
};

function handlePrint(url: any) {
  printUrl(
    url,
    (rst) => {
      console.log("打印成功");
      tipState2.info = scan.value;
      tipState4.info = url;

      console.log(rst);
      tipState.info = t("printPage.打印成功");
      tipState.background = "green";
      scan.value = "";
    },
    (rst) => {
      console.log("打印失败");
      tipState2.info = scan.value + " " + rst == "undefined" ? "" : rst;
      tipState4.info = "";

      tipState.info = t("printPage.打印失败");
      tipState.background = "red";
      scan.value = "";
    },
    () => {
      showConfirmDialog({
        title: t("printPage.未设置打印机"),
        message: t("printPage.点击确认进入打印机设置界面"),
        confirmButtonText: t("confirm"),
        cancelButtonText: t("cancel"),
      })
        .then(() => {
          router.push("/printer");
          return;
        })
        .catch(() => {
          // on cancel
        });
    }, () => {}
  );
}
// const activeIcon = ref("https://fastly.jsdelivr.net/npm/@vant/assets/user-active.png");
// const inactiveIcon = ref(
//   "https://fastly.jsdelivr.net/npm/@vant/assets/user-inactive.png"
// );

// <Picker :state="statePrint" :title="t('labelPrint.请选择打印机')" @close="closePopupPrint" @confirm="handleChangePrint" @reload="reloadPrint"/>
//     <van-cell
//       :title="t('labelPrint.打印机')"
//       :value="statePrint.currentItem ? statePrint.currentItem.text : t(`labelPrint.请选择打印机`)"
//       icon="orders-o"
//       url=""
//       to=""
//       clickable
//       is-link
//       center
//       @click="showPopupPrint"
//     />

// const statePrint = reactive({
//   show: false,
//   option: [],
//   currentItem: null,
// });
// const reloadPrint = () => {
//   postRequest("/mock",[
//     {
//       value: "123456",
//       text: "dyj01",
//     },
//     {
//       value: "dyj02",
//       text: "dyj02",
//     },
//   ]).then((res) => {
//     if (res.status == 200) {
//       statePrint.option = res.data;
//       if (localStorage.get(STORAGE_PRINTER_KEY)) {
//     statePrint.currentItem = statePrint.option.find(
//       (item) => item.value === localStorage.get(STORAGE_PRINTER_KEY)
//     );
//   }
//     } else {
//       AppToast(t('labelPrint.获取打印机失败')+" "+res.message,"danger");
//     }
//   });
// };
// reloadPrint();
// // 打印机
// const showPopupPrint = () => {
//   statePrint.show = true;
// };
// const handleChangePrint = (e: any): void => {
//   const value = e.selectedOptions[0].value;
//   localStorage.set(STORAGE_PRINTER_KEY, value);
//   statePrint.currentItem = statePrint.option.find((item) => item.value === value);
//   statePrint.show = false;
//   AppToast(t("labelPrint.切换成功"));
// };
// const closePopupPrint = () => {
//   statePrint.show = false;
// };
</script>

<style lang="less" scoped></style>
